package org.javacore.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author liufan
 * @version 1.0
 * @date 2023/3/3 10:42
 */
public class CountDownLatchDemo2 {
    private final static int threadCount = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            executor.execute(() -> {
                try {
                    test(threadNum);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("所有程序员已完成任务");
        executor.shutdown();
    }

    private static void test(int threadCount) throws InterruptedException {
        Thread.sleep(100);
        System.out.println(String.format("程序员 -》%d 完成任务", threadCount));
        Thread.sleep(100);
    }
}
